package com.cv.platform.service.favourite;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.cv.framework.common.pojo.PageResult;
import com.cv.framework.common.utils.object.BeanUtils;
import com.cv.framework.mybatis.core.query.QueryWrapperX;
import com.cv.framework.security.core.utils.SecurityFrameworkUtil;
import com.cv.infra.api.file.FileApi;
import com.cv.platform.controller.platform.favourite.vo.CvVideoFavouriteRespVO;
import com.cv.platform.controller.platform.favourite.vo.CvVideoFavouriteSaveReqVO;
import com.cv.platform.controller.platform.favourite.vo.CvVideoFavouriteReqVO;
import com.cv.platform.controller.platform.label.vo.record.CvVideoLabelRespVO;
import com.cv.platform.dal.dataobject.favourite.CvVideoFavouriteDO;
import com.cv.platform.dal.dataobject.video.CvVideoDO;
import com.cv.platform.dal.es.index.video.CvVideoEntity;
import com.cv.platform.dal.mapper.favourite.CvVideoFavouriteMapper;
import com.cv.platform.service.label.CvVideoLabelService;
import com.cv.platform.service.video.CvVideoService;
import com.cv.system.api.user.UserApi;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 视频收藏业务层接口实现类
 *
 * @author Charles_XDXD
 */
@Service
public class CvVideoFavouriteServiceImpl implements CvVideoFavouriteService {

    @Resource
    private CvVideoFavouriteMapper cvVideoFavouriteMapper;

    @Resource
    private CvVideoService cvVideoService;

    @Resource
    private CvVideoLabelService cvVideoLabelService;

    @DubboReference
    private FileApi fileApi;

    @DubboReference
    private UserApi userApi;

    @Override
    public List<CvVideoEntity> getAllVideoFavouriteByUserId(Long userId) {
        if (ObjUtil.isEmpty(userId)) {
            return Collections.emptyList();
        }

        QueryWrapperX<CvVideoFavouriteDO> wrapper = new QueryWrapperX<CvVideoFavouriteDO>()
                .eq("user_id", userId);

        List<CvVideoFavouriteDO> cvVideoFavouriteDOList = cvVideoFavouriteMapper.selectList(wrapper);

        if (CollUtil.isEmpty(cvVideoFavouriteDOList)) {
            return Collections.emptyList();
        }

        List<CvVideoEntity> cvVideoEntityList = new ArrayList<>();
        for (CvVideoFavouriteDO recordDO : cvVideoFavouriteDOList) {
            CvVideoDO videoDO = cvVideoService.getVideoById(recordDO.getVideoId());

            if (ObjUtil.isEmpty(videoDO)) {
                continue;
            }

            cvVideoEntityList.add(CvVideoEntity.builder()
                    .id(videoDO.getId())
                    .userId(videoDO.getUserId())
                    .nickname(userApi.getNicknameById(videoDO.getUserId()))
                    .title(videoDO.getTitle())
                    .type(videoDO.getType())
                    .labels(cvVideoLabelService.getAllLabelByVideoId(videoDO.getId())
                            .stream().map(CvVideoLabelRespVO::getLabelName)
                            .collect(Collectors.toList()))
                    .viewCount(videoDO.getViewCount())
                    .thumbnail(videoDO.getThumbnail())
                    .publishTime(videoDO.getCreateTime())
                    .build());
        }
        return cvVideoEntityList;
    }

    @Override
    public Boolean getIsVideoFavourite(Long videoId) {
        if (ObjUtil.isNotEmpty(videoId)) {
            QueryWrapperX<CvVideoFavouriteDO> wrapper = new QueryWrapperX<CvVideoFavouriteDO>()
                    .eq("video_id", videoId)
                    .eq("user_id", SecurityFrameworkUtil.getLoginUserId());
            return cvVideoFavouriteMapper.exists(wrapper);
        }
        return false;
    }

    @Override
    public void saveVideoFavourite(CvVideoFavouriteSaveReqVO reqVO) {
        if (ObjUtil.isNotEmpty(reqVO)) {
            CvVideoFavouriteDO recordDO = BeanUtils.toBean(reqVO, CvVideoFavouriteDO.class);
            recordDO.setUserId(SecurityFrameworkUtil.getLoginUserId());
            cvVideoFavouriteMapper.insertOrUpdate(recordDO);
        }
    }

    @Override
    public void deleteVideoFavourite(Long videoId) {
        Long userId = SecurityFrameworkUtil.getLoginUserId();
        if (ObjUtil.isNotEmpty(videoId) && ObjUtil.isNotEmpty(userId)) {
            QueryWrapperX<CvVideoFavouriteDO> wrapper = new QueryWrapperX<CvVideoFavouriteDO>()
                    .eq("video_id", videoId)
                    .eq("user_id", userId);
            cvVideoFavouriteMapper.delete(wrapper);
        }
    }

    @Override
    public PageResult<CvVideoFavouriteRespVO> getVideoFavouritePage(CvVideoFavouriteReqVO reqVO) {
        PageResult<CvVideoFavouriteRespVO> pageResult = cvVideoFavouriteMapper.selectPage(reqVO);

        if (CollUtil.isEmpty(pageResult.getList())) {
            return PageResult.empty();
        }

        pageResult.getList().forEach(item -> {
            item.setNickname(userApi.getNicknameById(item.getUserId()));
            item.setThumbnailUrl(fileApi.getUrl(item.getThumbnail()));
        });

        return pageResult;
    }

    @Override
    public Integer getTotalCollectionCount() {
        return Math.toIntExact(cvVideoFavouriteMapper.selectCount());
    }

}
